<template>
  <view class="container">
    <!-- 页面头部 -->
    <view class="header" @tap="openYearPicker">
      <!-- 统计数据 -->
      <view class="statistics-summary">
        <view class="stat-item">
          <text class="stat-label">总费用</text>
          <text class="stat-value expense">¥{{ fuelStatistics.fuelTotalCosts }}</text>
        </view>
        <view class="stat-item">
          <text class="stat-label">综合油耗</text>
          <text class="stat-value fuelEconomy">{{ fuelStatistics.fuelTotalFuelEconomy }}L/100km</text>
        </view>
        <view class="stat-item">
          <text class="stat-label">总公里数</text>
          <text class="stat-value">{{ fuelStatistics.fuelTotalMileage }}km</text>
        </view>
      </view>

      <!-- 年份选择 -->
      <view class="year-picker-wrapper">
        <text>{{ currentYear === '全部' ? '全部' : currentYear + ' 年' }}</text>
        <up-icon name="arrow-down" class="year-picker-icon"></up-icon>
      </view>
    </view>

    <!-- 年份选择器 -->
    <up-picker :show="yearPickerShow" :columns="yearColumnsData" closeOnClickOverlay @confirm="handleYearConfirm"
      @cancel="handleYearCancel" @close="handleYearCancel">
    </up-picker>

    <!-- 加油记录列表 -->
    <view class="records-list">
      <view v-for="record in fuelRecords" :key="record.id" class="record-wrapper">
        <view class="record-item" @tap="toggleRecordDetails(record.id)"
          :class="{ expanded: expandedRecords.includes(record.id) }">
          <!-- 记录基本信息 -->
          <view class="record-header">
            <view class="record-date">
              <text class="date-dot"></text>
              <text class="date-text">{{ record.date }}</text>
            </view>
            <view class="record-amount">
              <text class="amount-value">¥{{ record.actual_amount }}</text>
            </view>
            <view class="record-key-stats">
              <text class="record-liters">{{ record.liters }}升</text>
              <view class="fuelEconomy-container">
                <text class="record-fuelEconomy-value"
                  :class="{ 'good': record.fuelEconomyColor === 'good', 'bad': record.fuelEconomyColor === 'bad' }">
                  {{ record.fuelEconomy }}
                </text>
                <text class="record-fuelEconomy-unit">升/100公里</text>
              </view>
            </view>

            <!-- 右侧：打开编辑删除菜单的操作按钮，3个点 -->
            <view class="record-actions" @tap.stop="showRecordOperateMenu(record)">
              <up-icon name="more-dot-fill" size="36rpx" color="#999"></up-icon>
            </view>
          </view>

          <!-- 记录详细信息 -->
          <view v-if="expandedRecords.includes(record.id)" class="record-details">
            <view class="detail-row">
              <view class="detail-item">
                <text class="detail-label">表显里程</text>
                <text class="detail-value">{{ record.mileage }} km</text>
              </view>
              <view class="detail-item">
                <text class="detail-label">本次里程</text>
                <text class="detail-value">{{ record.tripMileage }} km</text>
              </view>
            </view>
            <view class="detail-row">
              <view class="detail-item">
                <text class="detail-label">当前油价</text>
                <text class="detail-value">{{ record.price_per_liter }} 元/L</text>
              </view>
              <view class="detail-item">
                <text class="detail-label">油费成本</text>
                <text class="detail-value expense">{{ record.costPerKm }} 元/km</text>
              </view>
            </view>
            <view class="detail-row">
              <view class="detail-item">
                <text class="detail-label">油枪金额</text>
                <text class="detail-value expense">{{ record.oil_pump_amount }} 元</text>
              </view>
              <view class="detail-item">
                <text class="detail-label">实付金额</text>
                <text class="detail-value expense">{{ record.actual_amount }} 元</text>
              </view>
            </view>
            <view class="detail-row">
              <view class="detail-item">
                <text class="detail-label">优惠金额</text>
                <text class="detail-value discount">{{ record.discountAmount }} 元</text>
              </view>
              <view class="detail-item">
                <text class="detail-label">是否加满</text>
                <view v-if="record.is_full" class="is-full-tag success">加满</view>
                <view v-else class="is-full-tag danger">未加满</view>
              </view>
            </view>
          </view>
        </view>
      </view>

      <!-- 空状态 -->
      <up-empty v-if="fuelRecords.length === 0" text="暂无加油记录" mode="data" style="height: 400px;">
      </up-empty>
    </view>

    <!-- 加油记录操作菜单（编辑、删除） -->
    <up-action-sheet :show="recordOperateMenuShow" :actions="recordOperateMenuList" :cancel-text="'取消'" round="12rpx"
      @select="handleRecordOperateSelect" @close="recordOperateMenuShow = false"></up-action-sheet>

    <!-- 底部浮动按钮（添加加油记录） -->
    <up-float-button @tap="addRecord" bottom="100px" backgroundColor="#4096FF" color="#FFFFFF">
    </up-float-button>

    <!-- 删除确认弹窗 -->
    <up-modal :show="deleteDialogShow" :title="'确认删除'" :content="'确定要删除记录吗？'" closeOnClickOverlay showCancelButton
      @confirm="confirmDelete" @cancel="deleteDialogShow = false" @close="deleteDialogShow = false">
    </up-modal>
  </view>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { onShow } from '@dcloudio/uni-app'
import * as fillupApi from '../../api/fuel'
import * as carApi from '../../api/car'

// ======= 状态管理 =======
const fuelRecords = ref([])           // 加油记录列表
const currentCar = ref({})            // 当前车辆信息
const currentYear = ref('全部')        // 当前选择的年份
const yearPickerShow = ref(false)     // 年份选择器显示状态
const yearColumnsData = ref([])       // 年份选择器数据
const expandedRecords = ref([])       // 展开的记录ID列表
const deleteDialogShow = ref(false)   // 删除确认弹窗显示状态
const recordToDelete = ref(null)      // 待删除的记录ID

// 记录操作菜单（编辑、删除）
const recordOperateMenuShow = ref(false)
const currentActionRecord = ref(null)
const recordOperateMenuList = [
  { name: '编辑', color: '#4096FF' },
  { name: '删除', color: '#ff4d4f' }
]

// 头部合计数据
const fuelStatistics = ref({
  fuelTotalCosts: '0.00',
  fuelTotalFuelEconomy: '0.0',
  fuelTotalMileage: '0'
})


// ======= 年份筛选器相关函数 =======
// 初始化年份筛选器列数据（包含全部选项）
const initYearPicker = () => {
  // 生成近10年的年份选项
  const currentYear = new Date().getFullYear()
  const years = []
  for (let i = 0; i < 10; i++) {
    years.push(currentYear - i)
  }
  yearColumnsData.value = [
    ['全部', ...years]
  ]
}

// 打开年份筛选器
const openYearPicker = () => {
  yearPickerShow.value = true
}

// 年份筛选器确认处理
const handleYearConfirm = async (e) => {
  currentYear.value = e.value[0]
  await loadFuelRecords()
  yearPickerShow.value = false
}

// 年份筛选器取消处理
const handleYearCancel = () => {
  yearPickerShow.value = false
}


// ======= 数据加载相关函数 =======
// 加载车辆数据
const loadCarData = async () => {
  try {
    const car = await carApi.getCurrentCar()
    currentCar.value = car

    if (car && car.id) {
      initYearPicker()
      await loadFuelRecords()
    }
  } catch (error) {
    console.error('加载车辆数据失败:', error)
    uni.$u.toast('加载车辆数据失败')
  }
}

// 加载加油记录
const loadFuelRecords = async () => {
  if (!currentCar.value || !currentCar.value.id) return

  try {
    // 从API获取包含计算属性和统计数据的结果
    const result = await fillupApi.getFuelRecords(
      currentCar.value.id,
      currentYear.value,
    )

    // 重置展开状态
    expandedRecords.value = []

    // 按日期降序排列
    fuelRecords.value = result.fuelRecords.sort((a, b) => new Date(b.date) - new Date(a.date))

    // 更新统计数据
    fuelStatistics.value = result.fuelStatistics
  } catch (error) {
    console.error('加载加油记录失败:', error)
    uni.$u.toast('加载加油记录失败')
  }
}


// ======= 记录操作相关函数 =======
// 切换记录详情展开状态
const toggleRecordDetails = (recordId) => {
  const index = expandedRecords.value.indexOf(recordId)
  if (index > -1) {
    expandedRecords.value.splice(index, 1)
  } else {
    expandedRecords.value.push(recordId)
  }
}

// 打开记录操作菜单
const showRecordOperateMenu = (record) => {
  currentActionRecord.value = record
  recordOperateMenuShow.value = true
}

// 记录操作菜单选择
const handleRecordOperateSelect = (item) => {
  if (item.name === '编辑') {
    editRecord(currentActionRecord.value)
  } else if (item.name === '删除') {
    deleteRecord(currentActionRecord.value.id)
  }
  recordOperateMenuShow.value = false
}

// 编辑记录
const editRecord = (record) => {
  // 跳转到编辑页面
  uni.navigateTo({
    url: `/pages/fuel/form?carId=${currentCar.value.id}&recordId=${record.id}`
  })
}

// 添加记录
const addRecord = () => {
  // 跳转到添加页面
  uni.navigateTo({
    url: `/pages/fuel/form?carId=${currentCar.value.id}`
  })
}

// 删除记录
const deleteRecord = (recordId) => {
  recordToDelete.value = recordId
  deleteDialogShow.value = true
}

// 确认删除
const confirmDelete = async () => {
  if (!recordToDelete.value) return

  try {
    const success = await fillupApi.deleteFuelRecord(recordToDelete.value)

    if (success) {
      await loadFuelRecords()
      deleteDialogShow.value = false
      uni.$u.toast('删除成功')
    } else {
      uni.$u.toast('删除失败')
    }
  } catch (error) {
    console.error('删除记录失败:', error)
    uni.$u.toast('删除失败，请重试')
  }
}


// ======= 初始化 =======
const initApp = async () => {
  const app = getApp();
  await app.waitForDBReady();
  console.log('加载加油数据...');
  await loadCarData();
}

onMounted(async () => {
  await initApp();
});

onShow(async () => {
  await initApp();
})
</script>

<style lang="scss" scoped>
/* 容器样式 */
.container {
  padding: 20rpx;
  background-color: #f5f5f5;
  min-height: 100vh;
}

/* 页面头部 */
.header {
  background: #fff;
  border-radius: 12rpx;
  padding: 30rpx;
  margin-bottom: 30rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
  display: flex;
  justify-content: flex-end;
  align-items: center;
}

.year-picker-wrapper {
  display: flex;
  align-items: center;
  border-radius: 8rpx;
}

.year-picker-wrapper text {
  font-size: 28rpx;
  color: #333;
}

.year-picker-icon {
  margin-left: 8rpx;
  font-size: 24rpx;
  color: #999;
}

/* 记录列表 */
.records-list {
  margin-bottom: 120rpx;
}

.record-wrapper {
  margin-bottom: 20rpx;
}

/* 记录项 */
.record-item {
  background: #fff;
  border-radius: 12rpx;
  padding: 24rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
  transition: all 0.3s;
}

.record-item.expanded {
  border-bottom: 1px solid #f0f0f0;
}

/* 记录头部 */
.record-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.record-amount {
  text-align: center;
  flex: 1;
}

.amount-value {
  font-size: 32rpx;
  font-weight: bold;
  color: #ff4d4f;
}

.record-date {
  display: flex;
  align-items: center;
}

.date-dot {
  width: 16rpx;
  height: 16rpx;
  background-color: #1890ff;
  border-radius: 50%;
  margin-right: 12rpx;
  display: inline-block;
}

.date-text {
  font-size: 30rpx;
  color: #333;
  font-weight: 500;
}

.record-key-stats {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
}

.record-liters {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.record-fuelEconomy {
  font-size: 26rpx;
  color: #666;
  margin-top: 4rpx;
}

/* 记录操作按钮 */
.record-actions {
  padding-left: 20rpx;
  display: flex;
  align-items: center;
}

/* 记录详情 */
.record-details {
  margin-top: 20rpx;
  padding: 20rpx;
  background-color: #f5f5f5;
  border-radius: 8rpx;
}

.detail-row {
  display: flex;
  justify-content: space-between;
  margin-bottom: 16rpx;
}

.detail-row:last-child {
  margin-bottom: 0;
}

.detail-item {
  flex: 1;
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  align-items: center;
  padding: 0 12rpx;
}

.detail-item:first-child {
  padding-left: 0;
}

.detail-item:last-child {
  padding-right: 0;
}

/* 统计数据样式 */
.statistics-summary {
  display: flex;
  flex: 1;
  gap: 15rpx;
  margin-right: 15rpx;
}

.stat-item {
  flex: 1;
  text-align: center;
}

.stat-value {
  font-size: 24rpx;
  font-weight: bold;
  color: #333;
  display: block;
}

.stat-value.expense {
  color: #ff4d4f;
}

.stat-value.fuelEconomy {
  color: #1890ff;
}

.stat-label {
  font-size: 20rpx;
  color: #999;
  display: block;
  margin-bottom: 6rpx;
}

/* 油耗显示样式 */
.fuelEconomy-container {
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: flex-end;
}

.record-fuelEconomy-value {
  font-size: 26rpx;
  font-weight: 500;
}

.record-fuelEconomy-value.good {
  color: #52c41a;
}

.record-fuelEconomy-value.bad {
  color: #ff4d4f;
}

.record-fuelEconomy-unit {
  font-size: 22rpx;
  color: #333;
  margin-left: 4rpx;
}

.detail-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10rpx 0;
}

.detail-label {
  font-size: 28rpx;
  color: #666;
}

.detail-value {
  font-size: 28rpx;
  color: #333;
}

.detail-value.expense {
  color: #ff4d4f;
  font-weight: 500;
}

.detail-value.discount {
  color: #52c41a;
}

/** 是否加满 */
.is-full-tag {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  font-size: 20rpx;
  height: 32rpx;
  padding: 0 12rpx;
  border-radius: 4rpx;
  background-color: transparent;
  margin-left: 12rpx;
  line-height: 1;
}

.is-full-tag.success {
  color: #52c41a;
  border: 1px solid #52c41a;
}

.is-full-tag.danger {
  color: #ff4d4f;
  border: 1px solid #ff4d4f;
}

/* 按钮样式 */
.cancel-button {
  border: 1px solid #ddd;
  color: #666;
}

.confirm-button {
  background-color: #4096FF;
  color: #fff;
}
</style>